package net.garbage;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author Jose Martin Rozanec;
 */
public class RemoteFileInputStream extends InputStream {
    private NetPortToServer port;
    private DataInputStream inputStream;
    private int bytesAvailable;

    RemoteFileInputStream(String host, int portnum, String filename) throws IOException {
        port = new NetPortToServer(host, portnum);
        inputStream = port.getInputStream();
        port.writeUTF(filename);
        port.flush();
        bytesAvailable = port.readInt();
        if (bytesAvailable < 0) {
            throw new IOException();
        }
    }

    public int available() throws IOException {
        return bytesAvailable;
    }

    public int read() throws IOException {
        bytesAvailable--;
        if (bytesAvailable == 0) {
            return -1;
        }
        return inputStream.read();
    }
}